package com.dji.system.core;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.dji.bean.Autowired;
import com.dji.bean.Compoment;
import com.dji.common.utils.PropertiesUtil;
import com.dji.system.core.nio.CharsetCodecFactory;
import com.dji.system.core.nio.ClientMessageHandlerAdapter;
import com.dji.system.core.nio.IoServiceAdapter;

@Compoment
public class NIOClient {
	@Autowired
	private IoServiceAdapter ioServiceAdapter;
	@Autowired
	private CharsetCodecFactory charsetCodecFactory;
	@Autowired
	private ClientMessageHandlerAdapter clientMessageHandlerAdapter;
	private SocketConnector connector;
	private ConnectFuture future;
	private IoSession session;

	public boolean connect() {
		// 创建一个socket连接
		connector = new NioSocketConnector();
		// 设置链接超时时间
		connector.setConnectTimeoutMillis(3000);
		// 获取过滤器链
		DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();
		// 添加编码过滤器 处理乱码、编码问题
		filterChain.addLast("codec", new ProtocolCodecFilter(charsetCodecFactory));
		// 消息核心处理器
		connector.setHandler(new ClientMessageHandlerAdapter());
		// 连接服务器，知道端口、地址
		connector.addListener(ioServiceAdapter);
		future = connector.connect(new InetSocketAddress(PropertiesUtil.getString("nio.remote.server.ip"),
				PropertiesUtil.getInt("nio.remote.server.port")));
		// 等待连接创建完成
		future.awaitUninterruptibly();
		// 获取当前session
		session = future.getSession();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				CloseFuture future = session.getCloseFuture();
				future.awaitUninterruptibly(1000);
				connector.dispose();
			}
		});
		return true;
	}

	public SocketConnector getConnector() {
		return connector;
	}

	public IoSession getSession() {
		return session;
	}
}
